package com.hailiang.saas.auth.web.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

@AutoConfigureAfter(DataSourceAutoConfiguration.class)
@Configuration
@MapperScan(value = {"com.hailiang.saas.auth.saas-auth.dal.dao" }, sqlSessionTemplateRef = "sqlSessionTemplate")
public class DataSourceConfiguration {

    @Autowired
    DataSource dataSource;

    @Bean("sqlSessionFactory")
    @Primary
    public SqlSessionFactory initSqlSessionFactory() throws Exception {

        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();

        factoryBean.setDataSource(dataSource);
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        factoryBean.setMapperLocations(resolver.getResources("classpath*:mapper/*.xml"));
        factoryBean.setTypeAliasesPackage("com.hailiang.saas.auth.saas-auth.dal.entity");
        return factoryBean.getObject();
    }

    @Bean("sqlSessionTemplate")
    @Primary
    public SqlSessionTemplate initSqlSessionTemplate() throws Exception {
        return new SqlSessionTemplate(initSqlSessionFactory());
    }

}